(function( $, window ) {
  var MediaManager = {
    index: 1,
    currentAttachments: [],
    currentAttachmentId: 0,
    rowId: 0,
    canceledIds: [],
    uploadingIds: [],
    uploadedIds: [],

    // actions
    init: function() {
      var that = this;
    },

    upload: function(key) {

      if (UploadManager.leftFileSize < 1) {
        alert("最多上传了1份文件。");
        return;
      }

      var params = {
        "uploadCallback": this.setAttachment,
        "progressallCallback": this.updateProgress,
      };

      var id = UploadManager.upload(params);
      var rowId;
      window.rowId = rowId;

    },


    cancelUpload: function(obj) {
      var bar = $(obj).parents(".progressbar");
      var id = bar.attr("id").replace("progress_", "");

      MediaManager.addCanceled($(obj).attr("class"));

      bar.remove();
      MediaManager.checkUploadTrigger();
      UploadManager.queue[id].uploading = false;
      UploadManager.queue[id].uploadCallback = function(data){

      };
    },

    checkUploadTrigger: function() {
      var row = $("#" + window.rowId);

      var count1 = row.find(".items>div").length;
      var count2 = row.find(".progressbar").length;
      var count = count1 + count2;
      if (count < 2) {
        row.find(".upload-trigger").removeClass("hide");
      } else {
        row.find(".upload-trigger").addClass("hide");
      }

      $(".uploaded-count").text(this.currentAttachments.length);

      //fixme, 放这里好吗？
      window.updateFileTypeLink();
    },

    isCanceled: function(id){
        return _.findIndex(MediaManager.canceledIds, function(o) { return o == id; }) != -1;
    },

    updateProgress: function(progress, id, name, fileinputId) {
      if (MediaManager.isCanceled(id)) { return; }

      MediaManager.addUploading(id);

      $(".step-1-c").addClass("hide");
      $(".step-2-c").removeClass("hide");
      $(".step-dot-2").addClass("step-dot-active");


      var that = this;

      var trigger = $(".files-container");
      if ($("."+ id).length < 1) {
        trigger.append('<div id="progress_'+ fileinputId +'" class="progressbar" style="position:relative;width:90%;"><div class="bar">&nbsp;</div><div class="name">'+name+'</div><a class="'+ id +'" style="z-index:999;position:absolute;top:1px;right:-15px" href="javascript:;" onclick="MediaManager.cancelUpload(this)"><img src="/img/icon_remove.png" width="13px" ></a></div>');
      }

      setTimeout(function(){
          $("."+ id).parents(".progressbar").find(".bar").css("width", progress + '%');
        MediaManager.checkUploadTrigger();
      }, 100);
    },


    removeAttachment: function(attachmentId) {

      var that = this;
      if (confirm("确定删除吗？")) {
         var data = {
            //id: rowId.replace("row_", ""),
            attachment_id: attachmentId,
          }
          $.ajax("/attachment/cancel", {
            data : JSON.stringify(data),
            contentType : 'application/json',
            type : 'POST'
          }).done(function(data){
            if (data.success) {
            }
          });

        $(".download_"+attachmentId).remove();

        UploadManager.fileSizePlus();

        setTimeout(function(){
          MediaManager.checkUploadTrigger();
        }, 100);

        _.remove(this.currentAttachments, function(id){
          return id === attachmentId;
        });
      }
    },


    updateCounter: function() {
      $(".uploaded-count").text(this.uploadedIds.length);
      $(".uploading-count").text(this.uploadingIds.length);
    },

    addUploading: function(id){
     var isAdded = _.findIndex(MediaManager.uploadingIds, function(o) { return o == id; }) != -1;
     if (!isAdded) {
      this.uploadingIds.push(id);
      this.updateCounter();
     }

    },

    addUploaded: function(id){
     this.uploadedIds.push(id);
     _.remove(this.uploadingIds, function(_id){return _id === id});
     this.updateCounter();
    },

    addCanceled: function(id){
     this.canceledIds.push(id);
     _.remove(this.uploadingIds, function(_id){return _id === id});
     _.remove(this.uploadedIds, function(_id){return _id === id});
     this.updateCounter();
    },

    setAttachment: function(attachment, id) {
      var that = this;
      var result = attachment.success;
      var msg = attachment.message;
      attachment = attachment.data;

      console.log("result is "+result+", message "+msg+", old version name "+$("#version_name").text());
      if(result==false){
        alert(msg);
        return;
      }
      if (MediaManager.isCanceled(id)) { return; }

      MediaManager.addUploaded(id);
      //if (!$("#pack_title").text()) {
      //  $("#pack_title").text(attachment.name.replace(/\.[^\.]+$/gi, ""));
      //}
      //if (!$("#version_name").text()) {
      //  $("#version_name").text(attachment.verName.replace(/\.[^\.]+$/gi, ""));
      //}
      //if (!$("#version_code").text()) {
      //  $("#version_code").text(attachment.verCode.replace(/\.[^\.]+$/gi, ""));
      //}

      //update attachment
      if (window.updateAttachment) {
        window.updateAttachment(attachment);
        window.updateAttachment = null;
      }

      MediaManager.currentAttachments.push(attachment.id);
      MediaManager.currentAttachmentId = attachment.id;
      var row = $(".files-container");

      row.append("<div style='position:relative' class='download_"+ attachment.id +"'><a class='hidetexta' style='margin-right: 5px;line-height: 1.5em;' href='/attachments/"+attachment.id+"/download'>"+ attachment.name +"</a> <a style='z-index:999' href='javascript:MediaManager.removeAttachment(" + attachment.id + ")'><img src='/img/icon_remove.png' width='13px' ></a><div>");

      setTimeout(function(){
        MediaManager.checkUploadTrigger();
      }, 100);

      $("."+ id).parents(".progressbar").remove();
      UploadManager.fileSizeMinus();

      $("#confirm-img").attr("src", "/img/icon_confirm_upload_active.png");
    },

    submit: function() {
      var that = this;

      //prepare
      var row = $(".form");
      var summary = row.find("textarea.summary").val();
      var menuName = row.find("#menuName").text();
      var menuUnitPrice = row.find("#menuUnitPrice").val();
      var menuDiscount = row.find("#menuDiscount").val();

      //validate
      if (this.currentAttachments.length < 1) {
        alert("请上传图片");
        return;
      }

      if (menuName.length < 1) {
        alert("menuName is null!");
        return;
      }
      if (menuUnitPrice.length < 1) {
        alert("menuUnitPrice is null");
        return;
      }
      if (menuDiscount.length < 1) {
        alert("menuDiscount is null");
        return;
      }


      //prepare data
      var data = {
        //title: title,
        name: menuName,
        unitPrice: menuUnitPrice,
        discount: menuDiscount,
        description:summary,
        attachmentId:this.currentAttachmentId,
        attachments: this.currentAttachments,
        date: HMUtil.today(),
      };

      console.log("data", data);

      $.ajax("/menu", {
        data : JSON.stringify(data),
        contentType : 'application/json',
        type : 'POST'
      }).done(function(data){
        if (data.success) {
          $(".step-2-c").addClass("hide");
          $(".step-3-c").removeClass("hide");
          $(".step-dot-3").addClass("step-dot-active");
        }
      });

    },

    clearStash: function() {
      this.currentAttachments = [];
    },

  };

  window.MediaManager = MediaManager;
  MediaManager.init();
}( jQuery, window ));

//setup
$.facebox.settings.closeImage = '/js/facebox/closelabel.png';
$.facebox.settings.loadingImage = '/js/facebox/loading.gif';
